package com.setup.trac.controller;

import java.util.LinkedList;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.setup.trac.pojo.Allegati;
import com.setup.trac.pojo.Progetti;
import com.setup.trac.pojo.condition.AllegatiFinderBySessioneUtenteWeb;
import com.setup.trac.service.ManageTicketService;
import com.setup.trac.service.SearchService;
import com.setup.trac.util.SQLCondition;
import com.setup.trac.util.TracSetupUtil;
import com.setup.trac.web.form.TicketForm;

public class AllegatoController extends SimpleFormController {

	private ManageTicketService manageTicketService;
	private SearchService searchService;
	private CommonsMultipartResolver multipartResolver;
	private int maxFileSize;
	private TracSetupUtil tracSetupUtil;

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		TicketForm tf = (TicketForm) command;

		byte[] contents = tf.getFile();
		CommonsMultipartFile theFile = (CommonsMultipartFile) ((LinkedList<MultipartFile>) ((DefaultMultipartHttpServletRequest) request)
				.getMultiFileMap().get("file")).get(0);
		Allegati allegato = new Allegati();
		allegato.setAllegato(contents);
		if (null != tf.getNomeFile() && !"".equals(tf.getNomeFile())) {
			allegato.setNome(tf.getNomeFile());
		} else {
			allegato.setNome(theFile.getOriginalFilename());
		}
		allegato.setSessioneUtente(request.getSession().getId());
		allegato.setTemporaneo(true);
		allegato.setContentType(theFile.getContentType());
		String theMD5 = getTracSetupUtil().getMD5Checksum(contents);
		allegato.setMd5(theMD5);
		manageTicketService.insertAllegato(allegato);

		String idProgetto = request.getParameter("idProgetto");
		String idOwner = request.getParameter("idOwner");
		String idTicket = request.getParameter("idTicket");
		String idUtente = request.getParameter("idUtente");
		if (idTicket != null) {
			tf.setIdTicket(idTicket);
			tf.setIdOwner(idOwner);
		}
		tf.setIdUtente(idUtente);

		Progetti progetto = searchService.findProgettoById(idProgetto);
		tf.setDescrizioneProgetto(progetto.getDescrizione());
		// azzero il nome del file
		tf.setNomeFile(null);
		// carico gli allegati
		SQLCondition sqlCondition = new AllegatiFinderBySessioneUtenteWeb(
				request.getSession().getId());
		Allegati[] listaAllegatiTemporanei = getSearchService().find(new Allegati[0], sqlCondition,Allegati.class);

		request.setAttribute("allegati", listaAllegatiTemporanei);

		request.setAttribute("ticket", command);
		ModelAndView mv = new ModelAndView(getSuccessView());
		return mv;
	}

	public ManageTicketService getManageTicketService() {
		return manageTicketService;
	}

	public void setManageTicketService(ManageTicketService manageTicketService) {
		this.manageTicketService = manageTicketService;
	}

	public SearchService getSearchService() {
		return searchService;
	}

	@Override
	protected ModelAndView showForm(HttpServletRequest request,
			HttpServletResponse response, BindException errors, Map controlModel)
			throws Exception {

		return super.showForm(request, response, errors, controlModel);
	}

	public void setSearchService(SearchService searchService) {
		this.searchService = searchService;
	}

	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		SQLCondition sqlCondition = new AllegatiFinderBySessioneUtenteWeb(
				request.getSession().getId());
		Allegati[] listaAllegatiTemporanei = getSearchService().find(new Allegati[0], sqlCondition,Allegati.class);

		request.setAttribute("allegati", listaAllegatiTemporanei);

		return super.handleRequest(request, response);
	}

	public CommonsMultipartResolver getMultipartResolver() {
		return multipartResolver;
	}

	public void setMultipartResolver(CommonsMultipartResolver multipartResolver) {
		this.multipartResolver = multipartResolver;
	}

	public int getMaxFileSize() {
		return maxFileSize;
	}

	public void setMaxFileSize(int maxFileSize) {
		this.maxFileSize = maxFileSize;
	}

	public TracSetupUtil getTracSetupUtil() {
		return tracSetupUtil;
	}

	public void setTracSetupUtil(TracSetupUtil tracSetupUtil) {
		this.tracSetupUtil = tracSetupUtil;
	}
	
	@Override
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder)
		throws ServletException {
 
		// Convert multipart object to byte[]
		binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
 
	}


}
